﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections;
using OpalisConsole.Class;
using OpalisConsole.EndUserService;
using System.Globalization;
using System.Threading;

namespace OpalisConsole.Views.User_Imaging
{
    public partial class Scheduling : Page
    {
        public static DateTime sTime;
        private DateTime previous;
        public Scheduling()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (App.Current.Resources["Computer_ID"].Equals("Not Approved"))
            {
                this.NavigationService.Navigate(new System.Uri("/User_Imaging/Registration", System.UriKind.Relative));
            }
            else
            {
                if (App.Current.Resources.Contains("DeveloperStatus"))
                {
                    if ((bool)App.Current.Resources["DeveloperStatus"]) { LinkUseUSMT.Visibility = System.Windows.Visibility.Visible; }
                }
                datePickerStart.BlackoutDates.AddDatesInPast();
                List<EntriesPerDate> dayList = (List<EntriesPerDate>)App.Current.Resources["DAY_LIST"];
                if (dayList != null)
                {
                    foreach (EntriesPerDate entry in dayList)
                    {
                        datePickerStart.BlackoutDates.Add(new CalendarDateRange(entry.Day));
                    }
                }
                SetupMessage();
            }
        }

        
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            App.Current.Resources.Remove("ScheduledDate");
            App.Current.Resources.Add("ScheduledDate", sTime);
            base.OnNavigatingFrom(e);
        }

        protected void SetupMessage()
        {
            txtSchedulingHeader.Text = "Select a Time for Your Windows 7 Fresh Start to Begin";

            ImagingText.Text = "The process will take up to 6 hours to complete.\n" +
                               "It is recommended that you schedule this process to " +
                               "begin when you leave for the day."+
                               "\n";
            ImagingCriteriaHeader.Text = "Your computer must meet the following " +
                                         "conditions at the scheduled time or your " +
                                         "fresh start will be cancelled.";

            txtACPower.Content = "    *    Plugged into AC Power";
            txtGenmillsOffice.Content = "    *    At a General Mills Office";
            txtDockingStation.Content = "    *    In a Docking Station or Attached to a Network Cable";
            txtPoweredOn.Content = "    *    Powered On";
            findNextSlot();
        }

        private void findNextSlot()
        {
            DateTime slot = DateTime.Today;

            bool foundDay = false;

            while (!foundDay)
            {
                if (!datePickerStart.BlackoutDates.Contains(new CalendarDateRange(slot)))
                {
                    foundDay = true;
                }
                else
                {
                    slot.AddDays(1);
                }
            }

            if (App.Current.Resources.Contains("ScheduledDate"))
            {
                DateTime timeSlot = (DateTime)App.Current.Resources["ScheduledDate"];
                datePickerStart.SelectedDate = timeSlot.Date;
                StartTime.Text = timeSlot.ToShortTimeString();

                sTime = timeSlot;

                previous = datePickerStart.SelectedDate.Value;
            }
            else
            {
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getOpenTimeSlotsCompleted += new EventHandler<getOpenTimeSlotsCompletedEventArgs>(proxy_getOpenTimeSlotsCompleted_init);
                proxy.getOpenTimeSlotsAsync(slot, (int)App.Current.Resources["MAX_ENTRIES_PER_HOUR"]);
            }
        }

        void proxy_getOpenTimeSlotsCompleted_init(object sender, getOpenTimeSlotsCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                throw new Exception();
            }
            else
            {
                foreach (DateTime timeSlot in e.Result)
                {
                    datePickerStart.SelectedDate = timeSlot.Date;
                    StartTime.Text = timeSlot.ToShortTimeString();

                    sTime = timeSlot;

                    previous = datePickerStart.SelectedDate.Value;
                    break;
                }
            }
            
        }
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new System.Uri("/User_Imaging/Summary", System.UriKind.Relative));
        }
        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            if (App.Current.Resources.Contains("DeveloperStatus"))
            {
                if ((bool)App.Current.Resources["DeveloperStatus"])
                {
                    this.NavigationService.Navigate(new System.Uri("/User_Imaging/UseUSMT", System.UriKind.Relative));
                }
                else
                {
                    this.NavigationService.Navigate(new System.Uri("/User_Imaging/SoftwareValidation", System.UriKind.Relative));
                }
            }
            else
            {
                this.NavigationService.Navigate(new System.Uri("/User_Imaging/SoftwareValidation", System.UriKind.Relative));
            }
            
        }
        private void datePickerStart_CalendarClosed(object sender, RoutedEventArgs e)
        {
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.getOpenTimeSlotsCompleted += new EventHandler<getOpenTimeSlotsCompletedEventArgs>(proxy_getOpenTimeSlotsCompleted);
            proxy.getOpenTimeSlotsAsync(datePickerStart.SelectedDate.Value, (int)App.Current.Resources["MAX_ENTRIES_PER_HOUR"]);
        }

        
        private void StartTime_GotFocus(object sender, RoutedEventArgs e)
        {
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.getOpenTimeSlotsCompleted += new EventHandler<getOpenTimeSlotsCompletedEventArgs>(proxy_getOpenTimeSlotsCompleted);
            proxy.getOpenTimeSlotsAsync(datePickerStart.SelectedDate.Value, (int)App.Current.Resources["MAX_ENTRIES_PER_HOUR"]);
        }

        void proxy_getOpenTimeSlotsCompleted(object sender, getOpenTimeSlotsCompletedEventArgs e)
        {
            List<TimeSlot> TimeList = new List<TimeSlot>();
            if (e.Error != null)
            {
                throw new Exception();
            }
            else
            {
                foreach (DateTime timeSlot in e.Result)
                {
                    TimeList.Add(new TimeSlot() { Time = timeSlot.ToShortTimeString(), Available = true });
                }
            }
            SchedulingWindow window = new SchedulingWindow(TimeList, 1);
            window.Closed += new EventHandler(window_Closed);
            window.Show();
        }

        void window_Closed(object sender, EventArgs e)
        {
            if (((SchedulingWindow)sender).DialogResult.Equals(true))
            {
                StartTime.Text = ((TimeSlot)((SchedulingWindow)sender).timeGrid.SelectedItem).Time.ToString();
                DateTime date = datePickerStart.SelectedDate.Value;
                DateTime time = Convert.ToDateTime(StartTime.Text);

                DateTime ScheduledDateTime = new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);
                sTime = ScheduledDateTime;
            }
            else
            {
                datePickerStart.SelectedDate = previous;
            }
        }

        private void datePickerStart_CalendarOpened(object sender, RoutedEventArgs e)
        {
            previous = datePickerStart.SelectedDate.Value;
        }
        private void imageSchedulingVideo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("http://spis.generalmills.com/sites/mshub/ContentLibrary/FS%20Scheduling%20Proj.wmv"), "_newWindow");
        }
    }
}
